<?php
declare(strict_types=1);

namespace app\admin\business;

use app\common\business\BusiBase;
use app\common\model\mysql\Module as ModuleModel;
use think\Exception;

class Module extends BusiBase
{
    public function __construct()
    {
        $this->model = new ModuleModel();
    }

    /**
     * 获取符合条件的所有栏目数据
     *
     * @param array $condition
     * @return array
     */
    public function getLists(array $condition = [])
    {
        if (!$condition) return [];
        try {
            $res = $this->model->getLists($condition);
        } catch (\Exception $e) {
            $this->errorLog("find module lists ".json_encode($condition)." error".$e->getMessage());
            return [];
        }
        if (!$res) return [];
        $result = $res->toArray();

        $pidArr = array_column($result, 'id');
        $childCount = [];
        if ($pidArr) {
            try {
                $childCount = $this->model->getChildCountByPid($pidArr);
            } catch (\Exception $e) {
                $this->errorLog('find child count by pid '.implode(',', $childCount).' error: '.$e->getMessage());
            }
        }
        $childCount = array_column($childCount, 'count', 'pid');

        foreach ($result as $key=>$val) {
            $result[$key]['childCount'] = $childCount[$val['id']] ?? 0;
        }

        return $result;
    }

    /**
     * 获取状态正常的所有栏目数据
     *
     * @param bool $field
     * @return array
     */
    public function getNormalModule($field = true, array $condition = [])
    {
        try {
            $res = $this->model->getNormalData($field, $condition);
        } catch (\Exception $e) {
            $this->errorLog('find normal module error: '.$e->getMessage());
            return [];
        }
        if (!$res) return [];
        return $res->toArray();
    }

    /**
     * 模块添加
     *
     * @param array $data
     * @return mixed
     * @throws Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function addModule(array $data)
    {
        $find = $this->model->getDataByName($data['name']);
        if ($find['id'] && $find['pid'] == $data['pid']) throw new Exception('该名称已存在');

        $insertId = $this->insert($data);
        return $insertId;
    }
}